/*************************************************************************
	> File Name: util.c
	> Author: gyl
	> Mail: gyldeyx@qq.com
	> Created Time: Sat 13 Feb 2021 03:01:49 PM CST
 ************************************************************************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/epoll.h>
#include <fcntl.h>
#include <sys/types.h>

#include "common.h"
#include "util.h"

int setnonblocking(int fd) {
    int old_option = fcntl(fd, F_GETFL);
    int new_option = old_option | O_NONBLOCK;
    fcntl(fd, F_SETFL, new_option);
    return old_option;
}

void addfd(int epollfd, int fd, bool enable_et) {
    struct epoll_event event;
    event.data.fd = fd;
    event.events = EPOLLIN;
    if (enable_et) {
        event.events |= EPOLLET;
    }
    epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &event);
    setnonblocking(fd);
}

void removefd(int epollfd, int fd) {
    epoll_ctl(epollfd, EPOLL_CTL_DEL, fd, 0);
    close(fd);
}
void modfd(int epollfd, int fd, int ev) {
    struct epoll_event event;
    event.data.fd = fd;
    event.events = ev | EPOLLET | EPOLLONESHOT | EPOLLRDHUP;
    epoll_ctl(epollfd, EPOLL_CTL_MOD, fd, &event);
}

//int write_log(char *buf, int length) {
//    write(pipefd[1], buf, length);
//}

/*void sig_handler(int sig) {
    int save_errno = errno;
    int msg = sig;
    send(pipefd[1], (char *)msg, 1, 0);
    errno = save_errno;
}

void addsig(int sig) {
    struct sigaction sa;
    memset(&sa, '\0', sizeof(sa));
    sa.sa_handler = sig_handler;
    sa.sa_flags |= SA_RESTART;
    sigfillset(&sa.sa_mask);
    assert(sigaction(sig, &sa, NULL) != -1);
}
*/

char *stohex(char *dst, int length)
{
    char buf_temp[MSG_MAXLEN] = {0};
    char *buf;
    buf = (char *)malloc(sizeof(char) * MSG_MAXLEN);
    memset(buf, '\0', MSG_MAXLEN);
    for (int i = 0, j = 0; i < length; i++) {
        if (dst[i] == '%') {
            buf[j++] = '\\';
            buf[j++] = 'x';
        } else buf[j++] = dst[i];
    }
    printf("util buf: %s\n", buf);
    memset(dst, '\0', length);
    int x = 0;
    unsigned long i = 0;
    while(*buf != '\0')
    {
        if(*buf == '\\') {
            strcpy(buf_temp,buf);
            *buf_temp = '0';
            *(buf_temp + 4) = '\0';
            i = strtoul(buf_temp, NULL, 16);
            dst[x] = i;
            buf += 3;        
        }
        else {
            dst[x] = *buf;            
        }
        x++;
        buf++;     
    }
    dst[x] = '\0';
    return dst;
}
